package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.BaseResultBean;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lileijian
 * @create 2021-12-05 23:48
 *
 *
 * 时间戳拦截器
 */
public class TimeFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取传入的时间
        String time = request.getParameter("time");

        //进行时间判断   是否超时
        if (time != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date parse = simpleDateFormat.parse(time);
            long time1 = parse.getTime();
            System.out.println("time1 = " + time1);

            long timeMillis = System.currentTimeMillis();
            System.out.println("timeMillis = " + timeMillis);

            if (Math.abs(timeMillis - time1) > 1800000 ) {
                System.out.println("时间未超时");
                return true;
            }
        }

        //以下为登录超时

        response.setContentType("application/json;charset=UTF-8");
        BaseResultBean bean = new BaseResultBean();
        bean.setCode(ExceptionDict.UNLOGIN);
        bean.setMsg("登录超时，请重新登录。");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return false;

    }
}
